package com.qls.web.modules.ord.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qls.ali.api.AliRemoteService;
import com.qls.core.entity.OrdGuest;
import com.qls.core.entity.OrdInvoiceInfo;
import com.qls.core.entity.OrdOrder;
import com.qls.core.entity.OrdWorkOrder;
import com.qls.core.utils.R;
import com.qls.web.common.utils.PageUtils;
import com.qls.web.common.utils.Sample;
import com.qls.web.modules.ord.service.*;
import com.qls.web.modules.sys.controller.AbstractController;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单信息
 *
 * @author doyoung
 */
@RestController
@RequestMapping("ord/order")
@Slf4j
public class OrdOrderController extends AbstractController {

    @Autowired
    private OrdOrderService ordOrderService;
    @Autowired
    private OrdWorkOrderService ordWorkOrderService;
    @Autowired
    private OrdGuestService ordGuestService;
    @Autowired
    private OrdInvoiceInfoService ordInvoiceInfoService;
    @Autowired
    private OrderDealService orderDealService;
    @Autowired
    private AliRemoteService aliRemoteService;


    /**
     * 发送短信
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("/sendMessage")
    public R sendMessage(@RequestParam Map<String, Object> params) {
        Integer id = Integer.valueOf(params.get("id").toString());
        OrdOrder ordOrderEntity = ordOrderService.getById(id);
        // 联系人电话
        String phone = ordOrderEntity.getPhone();
        // 联系人姓名
        String name = ordOrderEntity.getName();

        String accessKeyId = "LTAI5tPhK5KFvb7QuD1YGAVm";
        String accessKeySecret = "YYcIXYVwik4nhCOvh4MjeuspS2T486";     // 密钥

        String templateCode = "SMS_213286944";      // 模板编码
        String templateSignName = "行程旅游";        // 短信模板签名

        JSONObject jsonObject = new JSONObject();     // 短信json串
        jsonObject.put("name", name);
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setSignName(templateSignName);
        sendSmsRequest.setTemplateCode(templateCode);
        sendSmsRequest.setTemplateParam(jsonObject.toString());  // json串
        Sample sample = new Sample();
        R r = sample.sendMsg(accessKeyId, accessKeySecret, sendSmsRequest);
        if (Integer.parseInt(r.get("code").toString()) == 0) {
            ordOrderEntity.setIsMsg(1);
            ordOrderService.updateById(ordOrderEntity);
            return r;
        }
        return r;
    }

    /**
     * 订单列表
     *
     * @param params Map<String, Object>
     * @return R
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @RequiresPermissions("ord:order:list")
    public R list(@RequestBody Map<String, Object> params) {
        Integer dtId = getUserDtId();
        params.put("dtId", dtId);
        // 排序用的参数
        params.put("sidx", "id");
        params.put("ord", "desc");
        PageUtils page = ordOrderService.sqlQuryPage(params);
        return R.ok().put("page", page).put("me", getUserId());
    }

    /**
     * 入住人信息
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("/peo")
    @RequiresPermissions("ord:order:peo")
    public R peo(@RequestParam Map<String, Object> params) {
        Long orderCode = Long.parseLong((String) params.get("orderCode"));
        List<OrdGuest> ordGuestEntities = ordGuestService.getByOrderCode(orderCode);
        return R.ok().put("peo", ordGuestEntities);
    }

    /**
     * 发票信息
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("/invo")
    @RequiresPermissions("ord:order:invo")
    public R invo(@RequestParam Map<String, Object> params) {
        Long orderCode = Long.parseLong((String) params.get("ordCode"));
        OrdInvoiceInfo ordInvoiceInfoEntity = ordInvoiceInfoService.getByOrdCode(orderCode);
        return R.ok().put("invo_info", ordInvoiceInfoEntity);
    }

    /**
     * 查看备注
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("/getnote")
    public R getnote(@RequestParam Map<String, Object> params) {
        Long orderCode = Long.parseLong((String) params.get("id"));
        QueryWrapper<OrdWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderCode);
        List<OrdWorkOrder> ordWorkOrderEntities = ordWorkOrderService.getBaseMapper().selectList(wrapper);
        return R.ok().put("notes", ordWorkOrderEntities);
    }

    /**
     * 设置备注
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("/setnote")
    public R setnote(@RequestParam Map<String, Object> params) {
        Long orderCode = Long.parseLong((String) params.get("id"));
        String text = (String) params.get("info");
        String name = getUser().getUsername();
        OrdWorkOrder ordWorkOrderEntity = new OrdWorkOrder();
        ordWorkOrderEntity.setOrderId(orderCode);
        ordWorkOrderEntity.setName(name);
        ordWorkOrderEntity.setInfo(text);
        ordWorkOrderEntity.setTime(new Date());
        ordWorkOrderService.getBaseMapper().insert(ordWorkOrderEntity);
        return R.ok();
    }

    /**
     * 跟单 （订单状态不为1操作员可以进行跟单）
     *
     * @param params Map<String, Object>
     * @return R
     */
    @RequestMapping("lock")
    @RequiresPermissions("ord:order:lock")
    public R lock(@RequestParam Map<String, Object> params) {
        Integer userId = Math.toIntExact(getUserId());
        Long id = Long.parseLong((String) params.get("id"));
        String username = getUser().getUsername();
        return orderDealService.getLock(userId, id, username);
    }

    /**
     * 订单处理
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("deal")
    @RequiresPermissions("ord:order:deal")
    public R deal(@RequestParam Map<String, Object> params) {
        Long userId = getUserId();
        Long dealOrderPeo = Long.valueOf((String) params.get("dealOrderPeo"));
        // 跟单后，其他跟单人不能处理订单
        if (!dealOrderPeo.equals(userId)) {
            return R.error(-1, "跟单人不符");
        }
        return R.ok();
    }

    /**
     * 多数据源价格日历
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("rateslist")
    public R rateslist(@RequestParam Map<String, Object> params) {
        Integer id = Integer.valueOf((String) params.get("id"));
        List<Map<String, Object>> list = orderDealService.getRatesList(id);
        return R.ok().put("list", list);
    }

    /**
     * 下单
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("buy")
    public R buy(@RequestParam Map<String, Object> params) {
        return aliRemoteService.buy(params);
    }

    /**
     * 自采订单
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("buyother")
    public R buyOther(@RequestParam Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        Integer price = Integer.valueOf((String) params.get("price"));
        String orderCodeOther = (String) params.get("otherOrderCode");
        OrdOrder ordOrder = new OrdOrder();
        ordOrder.setPayPrice(price);
        ordOrder.setBuyOrderId(orderCodeOther);
        ordOrder.setId(id);
        ordOrder.setBuyStatus(3);
        ordOrderService.updateById(ordOrder);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("buyOrderId", orderCodeOther);
        jsonObject.put("code", 0);
        return aliRemoteService.callback(jsonObject);
    }

    /**
     * 关单/确认无房
     *
     * @param params Map<String, Object>
     * @return params
     */
    @RequestMapping("refuse")
    public R refuse(@RequestParam Map<String, Object> params) {
        Long id = Long.valueOf((String) params.get("id"));
        Integer optType = Integer.valueOf((String) params.get("optType"));
        Long userId = getUserId();
//        return orderDealService.refuse(id, optType, userId);
        return R.ok();
    }

    /**
     * 价格价格政策列表
     *
     * @param params
     * @return
     */
    @RequestMapping("pslist")
    @RequiresPermissions("ord:order:pslist")
    public R pslist(@RequestParam Map<String, Object> params) {
        Long userId = getUserId();
        int buyStatus = Integer.parseInt((String) params.get("buyStatus"));
        Long dealOrderPeo = Long.valueOf((String) params.get("dealOrderPeo"));
        // 跟单状态
        if (buyStatus == 0) {
            return R.error(-1, "未跟单");
        }
        // 跟单后，其他跟单人不能处理订单
        if (!dealOrderPeo.equals(userId)) {
            return R.error(-1, "跟单人不符");
        }
        return R.ok();
    }

    /**
     * 短信发送业务
     *
     * @param params
     * @return
     */
    @RequestMapping("sendmsg")
    public R sendMsg(@RequestParam Map<String, Object> params) {
//        Integer id = Integer.valueOf(params.get("id").toString());
//        OrdOrderEntity ordOrderEntity = ordOrderService.getById(id);
//
//        String phone = ordOrderEntity.getPhone();   // 联系人电话
//        String name = ordOrderEntity.getName();     // 联系人姓名
//
//        String accessKeyId = "LTAI5tPhK5KFvb7QuD1YGAVm";
//        String accessKeySecret = "YYcIXYVwik4nhCOvh4MjeuspS2T486";     // 密钥
//
//        String templateCode = "SMS_213286944";      // 模板编码
//        String templateSignName = "行程旅游";        // 短信模板签名
//
//        JSONObject jsonObject = new JSONObject();     // 短信json串
//        jsonObject.put("name", name);
//        SendSmsRequest sendSmsRequest = new SendSmsRequest();
//        sendSmsRequest.setPhoneNumbers(phone);
//        sendSmsRequest.setSignName(templateSignName);
//        sendSmsRequest.setTemplateCode(templateCode);
//        sendSmsRequest.setTemplateParam(jsonObject.toString());  // json串
//        Sample sample = new Sample();
//        R r = sample.sendMsg(accessKeyId, accessKeySecret, sendSmsRequest);
//        if(Integer.parseInt(r.get("code").toString()) == 0) {
//            ordOrderEntity.setIsMsg(1);
//            ordOrderService.updateById(ordOrderEntity);
//            return r;
//        }
//        return r;
        return R.ok();
    }
}
